package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class CartInfoApiController {
    @Autowired
    private CartInfoService cartInfoService;

    //添加时->加入购物车
    @PostMapping("/addToCart/{skuId}/{skuNum}")
    public Result addToCart(@PathVariable Long skuId, @PathVariable Integer skuNum, HttpServletRequest request) {
        //不是说无状态的吗?
        String userId = AuthContextHolder.getUserId(request);
        //没有真实id就用临时id
        if (StringUtils.isEmpty(userId)) {
            userId = AuthContextHolder.getUserTempId(request);
        }
        System.out.println("userId = " + userId);
        cartInfoService.addToCart(skuId, skuNum, userId);
        return Result.ok();
    }

    //添加时->查询购物车
    @GetMapping("/toCart/{sId}")
    public CartInfo toCart(@PathVariable Long sId) {
        return cartInfoService.toCart(sId);
    }

    /**
     * 初始化加载购物车集合 当前用户所有的购物车集合
     * 如果存在真实用户 将真实用户和临时用户 合并并清空临时用户购物车
     * 如果只存在临时用户 只查询临时用户
     */
    //去购物车结算
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        List<CartInfo> cartInfoList = cartInfoService.cartList(userId, userTempId);
        return Result.ok(cartInfoList);
    }

    //更新选中状态
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId, @PathVariable Integer isChecked) {
        cartInfoService.checkCart(skuId, isChecked);
        return Result.ok();
    }

    //删除单个购物车
    @DeleteMapping("/deleteCart/{skuId}")
    public Result deleteCart(@PathVariable Long skuId) {
        cartInfoService.deleteCart(skuId);
        return Result.ok();
    }

    //商品清单 购物车中已经勾选的商品集合???
    @GetMapping("/getCartInfoListByChecked")
    public List<CartInfo> getCartInfoListByChecked(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.getCartInfoListByChecked(userId);
    }


}
